package com.closeenough.app;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;

import com.closeenough.app.R;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.text.Html;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TimePicker;

public class InvitationSender extends Activity 
{	
	private ListView list_contact;
	private Button btn_send;

	/** 
	 * Called when the activity is first created. 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.invitation_sender);
		
		list_contact = (ListView) findViewById(R.id.list_contact);
		btn_send     = (Button) findViewById(R.id.btn_send);
		
		list_contact.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) 
			{
				EditText txt_mail = (EditText) findViewById(R.id.txt_mail);
				
				Cursor cursor_mail = getContentResolver().query(Email.CONTENT_URI,null,Email.CONTACT_ID +" = "+ id, null, null);
				int emailid = cursor_mail.getColumnIndex(Email.DATA);
				
				if(cursor_mail.moveToFirst())
				{
					String mailid = cursor_mail.getString(emailid);

					String mails = txt_mail.getText().toString();
					mails += ("".equals(mails) ? "" : ", ") + mailid;
						
					txt_mail.setText(mails);
				}
				else 
				{
					// El contacto no tiene mail.
				}
			}
		});
		
		btn_send.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View v) 
			{
				EditText txt_mail = (EditText) findViewById(R.id.txt_mail);
				DatePicker date_picker = (DatePicker) findViewById(R.id.date_picker);
				TimePicker time_picker = (TimePicker) findViewById(R.id.time_picker);
				
				Intent intent_send = new Intent(android.content.Intent.ACTION_SEND);
				
				//intent_send.setType("application/closeenough");				
				intent_send.setType("plain/text");
				
				//DateTime Ticks equivalent from http://stackoverflow.com/questions/3706306/c-sharp-datetime-ticks-equivalent-in-java				
				Calendar calendar = Calendar.getInstance();    
				calendar.set(Calendar.MILLISECOND, 0); // Clear the millis part. Silly API.
				calendar.set(date_picker.getYear(),
						date_picker.getMonth(),
						date_picker.getDayOfMonth(), 
						time_picker.getCurrentHour(), time_picker.getCurrentMinute(), 0);
				Date date = calendar.getTime();
				long millis = date.getTime(); // Millis since Unix epoch

				Bundle extras = getIntent().getExtras();
				int latitude = extras.getInt("latitude");
				int longitude = extras.getInt("longitude");
								
				/* Armar mensaje.
				 */
				String subject = getString(R.string.email_subject);
				String body = getString(R.string.email_text);

				intent_send.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ txt_mail.getText().toString() });                            
				intent_send.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
				intent_send.putExtra(android.content.Intent.EXTRA_TEXT, body);
				

				File data = null;
				try 
				{
					data = File.createTempFile("Invitation", ".closeenough");
					//FileWriter out = (FileWriter) GenerateCsv.generateCsvFile(data, "Name,Data1");
					GenerateCsv.generateCsvFile(data, latitude + "," + longitude + "," + millis + "," + getEmailAddress());
					intent_send.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(data));
				}
				catch (IOException e) {
					e.printStackTrace();
				}
				
				startActivity(intent_send);
				finish();
			}

			private String getEmailAddress()
			{
				Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
				Account[] accounts = AccountManager.get(getApplicationContext()).getAccounts();
				
				for (Account account : accounts)
				{
					if (emailPattern.matcher(account.name).matches())
					{
						//String possibleEmail = account.name;
						Log.d("le debug", "User email: " + account.name);
						return account.name;
					}
				}
				return "?"; 
			}
		});
		
		// Cargar la lista de contactos
		populateContactList();
	}

	/**
	 * 
	 * Populate the contact list based on account 
	 * currently selected in the account spinner.
	 */
	private void populateContactList()
	{
		// Build adapter with contact entries
		Cursor cursor = getContacts();
		String[] fields = new String[] {
				ContactsContract.Data.DISPLAY_NAME
		};
		
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
				fields, new int[] {R.id.contactEntryText});
		list_contact.setAdapter(adapter);
	}

	/** Obtener la lista de contactos.
	 *
	 * Obtains the contact list for the currently
	 * selected account.
	 *
	 * @return Un Cursor para el acceso a la lista 
	 * 		de contactos.
	 */
	private Cursor getContacts()
	{
		// Run query
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		String[] projection = new String[] {
				ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME
		};
		
		String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
				/*(mShowInvisible ? "0" : "1") + "'"*/;
		
		String[] selectionArgs = null;
		String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
		
		return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
	}

}

class GenerateCsv 
{
	public static FileWriter generateCsvFile(File sFileName,String fileContent)
	{
		FileWriter writer = null;
		
		try 
		{
			writer = new FileWriter(sFileName);
			writer.append(fileContent);
			writer.flush();
		
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				writer.close();
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return writer;
	}
}
